import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../providers/article_provider.dart';
import '../widgets/company_filter.dart';
import '../widgets/article_type_filter.dart';
import '../widgets/article_card.dart';
import '../widgets/mini_player.dart';
import '../config/app_theme.dart';

/// 首页屏幕
class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final RefreshController _refreshController = RefreshController(initialRefresh: false);
  int _pageNum = 1;
  bool _hasMore = true;

  @override
  void initState() {
    super.initState();
    _loadInitialData();
  }

  Future<void> _loadInitialData() async {
    final provider = Provider.of<ArticleProvider>(context, listen: false);
    try {
      await provider.fetchCompanyList();
      await provider.fetchArticleList(pageNum: 1);
    } catch (e) {
      debugPrint('加载数据失败: $e');
    }
  }

  Future<void> _onRefresh() async {
    _pageNum = 1;
    _hasMore = true;
    
    final provider = Provider.of<ArticleProvider>(context, listen: false);
    try {
      await provider.fetchArticleList(pageNum: _pageNum, refresh: true);
      _refreshController.refreshCompleted();
      
      if (provider.articleList.length >= provider.total) {
        _hasMore = false;
      }
    } catch (e) {
      _refreshController.refreshFailed();
    }
  }

  Future<void> _onLoading() async {
    if (!_hasMore) {
      _refreshController.loadNoData();
      return;
    }
    
    _pageNum++;
    final provider = Provider.of<ArticleProvider>(context, listen: false);
    
    try {
      await provider.fetchArticleList(pageNum: _pageNum);
      _refreshController.loadComplete();
      
      if (provider.articleList.length >= provider.total) {
        _hasMore = false;
        _refreshController.loadNoData();
      }
    } catch (e) {
      _pageNum--;
      _refreshController.loadFailed();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        centerTitle: true,
        toolbarHeight: 0,
        automaticallyImplyLeading: false,
      ),
      body: Stack(
        children: [
          // 背景渐变
          Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Color(0xFF171937), // 顶部深蓝
                  Color(0xFF111113), // 底部近黑
                ],
              ),
            ),
          ),
          // 顶部背景图片
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: IgnorePointer(
              ignoring: true,
              child: Image.asset(
                'assets/images/bg.png',
                height: 240,
                fit: BoxFit.cover,
                alignment: Alignment.topCenter,
                opacity: const AlwaysStoppedAnimation(0.85),
              ),
            ),
          ),
          Column(
            children: [
              // 让内容避开透明 AppBar 区域（仅状态栏高度）
              SizedBox(height: MediaQuery.of(context).padding.top + 8),
              // 公司筛选栏
              const CompanyFilter(),
              
              // 资讯类型筛选栏
              const ArticleTypeFilter(),
              
              // 资讯列表
              Expanded(
                child: Consumer<ArticleProvider>(
                  builder: (context, provider, child) {
                    if (provider.loading && provider.articleList.isEmpty) {
                      return const Center(child: CircularProgressIndicator());
                    }
                    
                    if (provider.articleList.isEmpty) {
                      return const Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.search, size: 64, color: AppTheme.textTertiary),
                            SizedBox(height: 16),
                            Text(
                              '暂无资讯',
                              style: TextStyle(
                                color: AppTheme.textTertiary,
                                fontSize: 16,
                              ),
                            ),
                          ],
                        ),
                      );
                    }
                    
                    return SmartRefresher(
                      controller: _refreshController,
                      enablePullDown: true,
                      enablePullUp: true,
                      onRefresh: _onRefresh,
                      onLoading: _onLoading,
                      header: const WaterDropHeader(),
                      footer: CustomFooter(
                        builder: (context, mode) {
                          Widget body;
                          if (mode == LoadStatus.idle) {
                            body = const Text('上拉加载更多');
                          } else if (mode == LoadStatus.loading) {
                            body = const CircularProgressIndicator();
                          } else if (mode == LoadStatus.failed) {
                            body = const Text('加载失败，点击重试');
                          } else if (mode == LoadStatus.canLoading) {
                            body = const Text('松手加载更多');
                          } else {
                            body = const Text('没有更多了');
                          }
                          return SizedBox(
                            height: 55.0,
                            child: Center(child: body),
                          );
                        },
                      ),
                      child: ListView.builder(
                        padding: const EdgeInsets.all(16).copyWith(bottom: 80),
                        itemCount: provider.articleList.length,
                        itemBuilder: (context, index) {
                          return ArticleCard(article: provider.articleList[index]);
                        },
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
          
          // 全局 Mini 播放器
          const Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: MiniPlayer(),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }
}

